package com.jdew.thkj.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.jdew.thkj.R;
import com.jdew.thkj.adapter.GoAdapter;
import com.jdew.thkj.base.BaseActivity;
import com.jdew.thkj.bean.SuperSearchBean;
import com.jdew.thkj.manager.AppConfig;
import com.jdew.thkj.network.RetrofitManager;
import com.jdew.thkj.network.api.RequestApi;
import com.jdew.thkj.onitemInterface.OnItemClickListener;
import com.jdew.thkj.utils.DeviceUtils;
import com.jdew.thkj.utils.MD5Utils;
import com.jdew.thkj.utils.RegexValidateUtils;
import com.jdew.thkj.utils.ToastUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by yangzai on 2018/8/14.
 */

public class GOActivity extends BaseActivity {
    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.recycleView)
    RecyclerView recycleView;
    @Bind(R.id.swipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;
    @Bind(R.id.nonetwork)
    TextView nonetwork;
    private int page = 1;
    private GoAdapter adapter;
    private boolean isLoading = true;
    private String ItemId;
    private String biaoti;
    private List<SuperSearchBean.DataBean.TbkDgMaterialOptionalResponseBean.ResultListBean.MapDataBean> list = new ArrayList<>();


    @Override
    public int bindLayout() {
        return R.layout.activity_go;
    }

    @Override
    public void initView(View view) {
        back.setVisibility(View.VISIBLE);
        sp = getSharedPreferences("user", Activity.MODE_PRIVATE);
        editor = sp.edit();
        back.setOnClickListener(this);
        nonetwork.setOnClickListener(this);
        biaoti = getIntent().getStringExtra("title");
        title.setText(biaoti);
        adapter = new GoAdapter(this, list);
        setRcycleview(recycleView, adapter);
        initRefresh();
        RequestData();
        setRecycleView();
        adapter.setItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (!RegexValidateUtils.isFastClick()) {
                    return;
                }
                if (sp.getString("SpareTwo", "").equals("")) {
                    startActivity(new Intent(GOActivity.this, LoginActivity.class));
                } else if (sp.getString("UserSjPhone", "").equals("") && (!sp.getString("SpareTwo", "").equals("1"))) {
                    toset("检测到您还没有绑定上级,请到我的页面绑定上级");
                } else {
                    ItemId = list.get(position).getNum_iid() + "";
                    Bundle b = new Bundle();
                    b.putSerializable("itemId", ItemId);
                    startActivity(TbProductDetailActivity.class, b);
                }
            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back: {
                finish();
            }
            break;
            case R.id.nonetwork: {
               RequestData();
            }
            break;
            default:
                break;
        }
    }

    public void RequestData() {
        if (!DeviceUtils.isNetworkAvalible(this)) {
            swipeRefreshLayout.setVisibility(View.GONE);
            nonetwork.setVisibility(View.VISIBLE);
            ToastUtils.getInstance(this).showMessage("网络连接错误请检查");
            return;
        } else {
            swipeRefreshLayout.setVisibility(View.VISIBLE);
            nonetwork.setVisibility(View.GONE);
        }
        String timesamp=RegexValidateUtils.getTime13();
        String numsamp=RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).GetActivity(page, RegexValidateUtils.getUniquePsuedoID(),timesamp,numsamp,MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp+numsamp+RegexValidateUtils.getUniquePsuedoID()+sp.getString("SignToken","")+"PageIndex"+page)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(JSONObject obj) {
                if (obj.getString("code").equals("0")) {
                    SuperSearchBean bean = JSONObject.parseObject(obj.toString(), SuperSearchBean.class);
                    if (null == bean.getData()) {
                        return;
                    }
                    if (page == 1) {
                        list.clear();
                    }
                    list.addAll(bean.getData().getTbk_dg_material_optional_response().getResult_list().getMap_data());
                    adapter.setDataList(list);
                    isLoading = false;
                    adapter.changeMoreStatus(adapter.LOADING_MORE);
                    swipeRefreshLayout.setRefreshing(false);
                }
            }
        });
    }

    public void RequestGo() {
        if (!DeviceUtils.isNetworkAvalible(this)) {
            swipeRefreshLayout.setVisibility(View.GONE);
            nonetwork.setVisibility(View.VISIBLE);
            ToastUtils.getInstance(this).showMessage("网络连接错误请检查");
            return;
        } else {
            swipeRefreshLayout.setVisibility(View.VISIBLE);
            nonetwork.setVisibility(View.GONE);
        }
        String timesamp=RegexValidateUtils.getTime13();
        String numsamp=RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).GetActivity(page, RegexValidateUtils.getUniquePsuedoID(),timesamp,numsamp,MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp+numsamp+RegexValidateUtils.getUniquePsuedoID()+sp.getString("SignToken","")+"PageIndex"+page)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(JSONObject obj) {
                if (obj.getString("code").equals("0")) {
                    SuperSearchBean bean = JSONObject.parseObject(obj.toString(), SuperSearchBean.class);
                    if (null == bean.getData()) {
                        return;
                    }
                    if (page == 1) {
                        list.clear();
                    }
                    list.addAll(bean.getData().getTbk_dg_material_optional_response().getResult_list().getMap_data());
                    adapter.setDataList(list);
                    isLoading = false;
                    adapter.changeMoreStatus(adapter.LOADING_MORE);
                    swipeRefreshLayout.setRefreshing(false);
                }
            }
        });
    }


    private void initRefresh() {
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 1;
                RequestData();
                swipeRefreshLayout.setRefreshing(false);
            }
        });
    }

    public void setRecycleView() {
        recycleView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
                LinearLayoutManager linearManager = null;
                if (layoutManager instanceof LinearLayoutManager) {
                    linearManager = (LinearLayoutManager) layoutManager;
                }
                int lastVisibleItemPosition = linearManager.findLastVisibleItemPosition();
                if (lastVisibleItemPosition + 1 == adapter.getItemCount()) {
                    boolean isRefreshing = swipeRefreshLayout.isRefreshing();
                    if (isRefreshing) {
                        adapter.notifyItemRemoved(adapter.getItemCount());
                        return;
                    }
                    if (!isLoading) {
                        isLoading = true;
                        page++;
                        RequestData();
                    }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
    }
}
